package com.booter.webflux.http.factory;

import com.booter.webflux.http.processor.CreateProcessor;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class HttpFactoryBean<T> implements FactoryBean<T> {

    private CreateProcessor processor;

    /**
     * 接口
     */
    private Class<T> cls;

    public HttpFactoryBean(Class<T> cls) {
        validateServiceInterface(cls);
        this.cls = cls;
    }


    @Override
    public T getObject() {
        return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{getObjectType()}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) {
                return processor.create(cls, method, args);
            }
        });
    }

    @Override
    public Class<T> getObjectType() {
        return cls;
    }

    private <T> boolean validateServiceInterface(Class<T> service) {
        if (!service.isInterface()) {
            throw new IllegalArgumentException("API declarations must be interfaces.");
        }
        if (service.getInterfaces().length > 0) {
            throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
        }
        return true;
    }

    public void setProcessor(CreateProcessor processor) {
        this.processor = processor;
    }
}
